<?php

namespace addons\kuerp\controller;

use addons\kuerp\model\Event as EventModel;
use addons\kuerp\model\AdminConfig;
use addons\kuerp\model\EventNeeds;
use addons\kuerp\model\Flow;
use addons\kuerp\model\Form;
use addons\kuerp\model\File;
use addons\kuerp\model\FormField;
use addons\kuerp\model\Staff;
use addons\kuerp\model\StaffSignIn;
use addons\kuerp\model\Message;
use addons\kuerp\model\Customers;
use addons\kuerp\model\Consume;
use addons\kuerp\model\Admin;
use app\admin\model\department\Admin as DepartmentAdmin;
use think\Db;
use think\Exception;
use think\Log;

/**
 * 日程接口
 */
class Event extends StaffApi
{
    protected $noNeedLogin = [];
    protected $noNeedRight = [];

    public function _initialize()
    {
        parent::_initialize();
    }
    //获取日程
    public function getEvent()
    {
        //开始时间
        $start_day = input('start_day');
        //结束时间
        $end_day = input('end_day');
        if (empty($start_day) || empty($end_day)) {
            $this->error('开始时间或结束时间不能为空');
        }
        if ($end_day < $start_day) {
            $this->error('开始时间不能小于结束时间');
        }
        $this->success('请求成功', EventModel::getTimeList($start_day, $end_day));
    }

    /**
     * 首页获取日程列表
     *
     * @ApiTitle    (首页获取日程列表)
     * @ApiSummary  (日 周 月)
     * @ApiMethod   (POST)
     * @ApiRoute    (/api/event/getIndexList)
     * @ApiParams   (name="type", type="integer", required=true, description="1 今日计划 2 本周计划 3 本月计划")
     * @ApiReturnParams   (name="code", type="integer", required=true, sample="0")
     * @ApiReturnParams   (name="msg", type="string", required=true, sample="返回成功")
     */
    public function getIndexList()
    {

        $where = [];
        $where['staff_id'] = $this->auth->id;

        $times = input('times', date('Y-m-d'));

        $where['start_time'] = ['between', [$times, date('Y-m-d', strtotime($times . '+1day'))]];
        $records = EventModel::where($where)->with([
            'staff',
            'customer'
        ])->field('id,staff_id,type,process,visits_number,customer_id,title,start_time,end_time,status,level,relation_id,use_time,createtime')->order('id desc')->select();
        foreach ($records as $key => $event) {
            $event->level = EventModel::getLevel($event->level);
            $event->status = EventModel::getStatus($event->status);
            $records[$key] = $event;
        }

        $this->success('请求成功', $records);
    }

    //获取列表
    public function getList()
    {
        $params = $this->request->post();
        $relation_id = input('relation_id', '', 'intval');
        $relation_type = input('relation_type', 'customer');
        $customer_id = input('customer_id');
        // 0未开始 1执行中2 已结束 3 已取消'
        $status = input('status', '');
        $type_tab = input('type_tab', '', 'intval');
        $event_type = input('event_type', '');
        $times = input('times', '');
        $actual_end_time = input('actual_end_time', '');
        $name = input('name', '');
        $limit = input("limit/d", 10);
        $where = [];
        if ($times) {
            $times = setTimes($times, 'time');
            $where['createtime'] = ['between', $times];
        }
        if ($actual_end_time) {
            $actual_end_time = setTimes($actual_end_time, 'time');
            $where['createtime'] = ['between', $actual_end_time];
        }
        $whereStaff = [];
        if ($relation_id) {
            $where['relation_type'] = $relation_type;
            $where['relation_id'] = $relation_id;
        } else {
            $whereStaff['staff_id'] = ['in', Staff::getMyStaffIds()];
            if (isset($params['type']) && $params['type']) {//客户分类
                if ($params['type'] == 1) {//我的创建
                    $whereStaff['staff_id'] = $this->auth->id;
                } elseif ($params['type'] == 2) {//下属创建
                    $whereStaff['staff_id'] = ['in', Staff::getLowerStaffId()];
                }
            }
        }
        if ($customer_id) {
            $where['customer_id'] = $customer_id;
        }
        if ($event_type) {
            $where['event_type'] = ['like', "%{$event_type}%"];
        }
        if ($status) {
            $where['status'] = ['in', explode(',', $status)];
        }
        $where['type'] = ['neq', 4];
        if ($type_tab) {
            $where['type'] = $type_tab;
        }
        if ($name) {
            $where['title'] = ['like', '%' . $name . '%'];
        }
        if (isset($params['id_list'])) {//日志 查询id列表
            $where = [];
            $whereStaff = [];
            $where['id'] = ['in', explode(',', $params['id_list'])];
        }
        $records = EventModel::where($where)->where($whereStaff)->with([
            'staff',
            'customer',
        ])->order('id desc')->paginate($limit)->toArray();

        $data = $records['data'];
        foreach ($data as $k => $v) {
            $v['level'] = EventModel::getLevel($v['level']);
            $v['status'] = EventModel::getStatus($v['status']);
            if ($v['use_time'] >= 60) {
                //按小时算
                $v['use_time'] = sprintf("%.2f", $v['use_time'] / 60) . '小时';
            } else {
                $v['use_time'] = $v['use_time'] ? $v['use_time'] . '分钟' : 0;
            }
            $data[$k] = $v;
        }

        $this->success('请求成功', [
            'total' => $records['total'],
            'per_page' => $records['per_page'],
            'current_page' => $records['current_page'],
            'last_page' => $records['last_page'],
            'data' => $data
        ]);
    }

    //获取列表
    public function getListNumber()
    {

        // 0未开始 1执行中2 已结束 3 已取消'
        $where['type'] = ['neq', 4];
        $whereStaff = function ($query) {
            $query->where('create_staff_id|staff_id', 'in', Staff::getMyStaffIds());
        };
        $where['status'] = 0;
        $event0 = EventModel::where($where)->where($whereStaff)->order('id desc')->count();
        $where['status'] = 1;
        $event1 = EventModel::where($where)->where($whereStaff)->order('id desc')->count();
        $where['status'] = 2;
        $event2 = EventModel::where($where)->where($whereStaff)->order('id desc')->count();
        $where['status'] = 3;
        $event3 = EventModel::where($where)->where($whereStaff)->order('id desc')->count();

        $this->success('请求成功', [
            'event0' => $event0,
            'event1' => $event1,
            'event2' => $event2,
            'event3' => $event3,
        ]);
    }

    //添加日程
    public function addEvent()
    {
        $params = $this->request->post();

        // 表单验证
        if (($result = $this->kuerpValidate($params, get_class(), 'create')) !== true) {
            $this->error($result);
        }
        try {
            $result = EventModel::createEvent($params);
        } catch (Exception $e) {
            $this->error($e->getMessage());
        }
        if ($result) {
            $this->success('添加成功');
        }
    }

    //编辑日程
    public function editEvent()
    {
        $params = $this->request->post();

        // 表单验证
        if (($result = $this->kuerpValidate($params, get_class(), 'edit')) !== true) {
            $this->error($result);
        }
        $event = EventModel::get($params['id']);
        if (empty($event)) {
            $this->error('日程不存在');
        }
        try {
            $result = EventModel::editEvent($params);
            $data = [
                'staff_id' => $this->auth->id,
                'customer_id' => $event['relation_id'],//客户id
                'relation_process' => '修改日程信息',//日程类型
                'relation_type' => StaffSignIn::EVENT_TYPE,//日程类型
                'relation_id' => $event['id'],//签到关联id
                'content' => '修改日程信息',
            ];
            //创建签到记录
            StaffSignIn::createSignIn($data);
        } catch (Exception $e) {
            $this->error($e->getMessage());
        }
        if ($result) {
            $this->success('修改日程成功');
        }
    }

    //获取详情
    public function getDetail()
    {
        $id = input('id');
        if (empty($id)) {
            $this->error('参数错误');
        }
        $event = EventModel::where(['id' => $id])->with(['staff', 'customer', 'contacts'])->find();
        if (empty($event)) {
            $this->error('日程不存在');
        }
        $event['status_text'] = EventModel::getStatus($event['status']);
        $event['is_revoke'] = 0;
        $event['is_operation'] = 0;
        if ($event['create_staff_id'] == $this->auth->id) {
            //是否可以撤销
            $event['is_revoke'] = 1;
        }
        if ($event['staff_id'] == $this->auth->id) {
            //是否可以操作
            $event['is_operation'] = 1;
        }

        Message::setRead(Message::EVENT_TYPE, $id, $this->auth->id);
        $this->success('请求成功', $event);
    }

    //客户需求
    public function addNeeds()
    {
        $event_id = input('event_id');
        $needs = input('needs');
        if (empty($event_id) || empty($needs)) {
            $this->error('参数不能为空');
        }
        $data = [
            'event_id' => $event_id,
            'staff_id' => $this->auth->id,
            'needs' => $needs
        ];
        $needs = new EventNeeds();
        $needs->save($data);

        $this->success('新增成功');

    }

    //客户需求列表
    public function getNeedsList()
    {
        $event_id = input('event_id');
        $where = ['event_id' => $event_id];

        $needs = new EventNeeds();
        $list = $needs->where($where)->order('id desc')->select();

        $this->success('请求成功', $list);

    }

    //添加日程进度
    public function addSign()
    {
        $location = input('location');
        $lng = input('lng');
        $lat = input('lat');
        $file_ids = input('file_ids');
        // 1 开始 2 到访 3 结束  4 回公司
        $event_process = input('event_process');
        $event_id = input('event_id');
        $content = input('content', '');
        $call_content = input('call_content', '');//通话内容
        $is_successful = input('is_successful', 0);//是否达成预期目的 1是 2否（完成时提交）
        $achieve_purpose = input('achieve_purpose', '');//达成目的
        $consume = input('consume/a');
        $car_type = input('car_type');//出行工具
        $car_number = input('car_number');//出行工具
        $start_mileage = input('start_mileage',0,'intval');//起始公里数
        $end_mileage = input('end_mileage',0,'intval');//起始公里数
        $back_mileage = input('back_mileage',0,'intval');//返程公里数
        $needs = input('needs');//客户需求
        $last_event = input('last_event');//下一行程

        $where = ['id' => $event_id];
        $event = EventModel::where($where)->find();
        if (empty($event)) {
            $this->error('日程不存在');
        }
        if ($event['process'] >= $event_process) {
            $this->error('日程状态修改错误');
        }
        $customer = Customer::where(['id' => $event['relation_id']])->find();
        if (empty($lng) && empty($lat)) {
            $distance = '';
        } elseif (empty($customer['lng']) && empty($customer['lat'])) {
            $distance = '';
        } else {
            $distance = getdistance($customer['lng'], $customer['lat'], $lng, $lat);
        }
        if (in_array($event['event_type'], ['客户服务_电话', '客户服务_微信', '售后服务_电话'])) {
            if ($event_process == 1) {
                $event_process_text = '开始任务';
            } else if ($event_process == 3) {
                $event_process_text = '完成任务';
            } else {
                $event_process_text = $event_process;
            }
        } else {
            $event_process_text = $event_process;
        }
        $data = [

            'staff_id' => $this->auth->id,
            'location' => $location,
            'lng' => $lng,
            'lat' => $lat,
            'file_ids' => $file_ids,
            'customer_id' => $event['relation_id'],//客户id
            'relation_type' => StaffSignIn::EVENT_TYPE,//日程类型
            'relation_id' => $event['id'],//签到关联id
            'relation_process' => $event_process_text,//进度
            'customer_status' => $customer['contract_status'],//成交状态
            'content' => $content ?? '',//处理结果
            'distance' => $distance,
        ];
        //存在通话内容
        if ($call_content) {
            $data['content'] = '处理结果:' . $data['content'] . '<br>电话内容:' . $call_content;
        }
        if ($car_type) {
            $data['content'] = '备注:' . $data['content'] . '<br>出行方式:' . $car_type;
            if ($start_mileage) {
                $data['content'] .= "($start_mileage)";
            }
        }
        if ($needs) {
            $data['content'] = '备注:' . $data['content'] . '<br>客户需求:' . $needs;
        }
        if ($end_mileage) {
            if ($end_mileage <= $event['start_mileage']) {
                $this->error('结束公里数不能小于起始公里数');
            }
            $data['content'] = '备注:' . $data['content'] . '<br>出行方式:' . $event['car_type'];
            if ($end_mileage) {
                $data['content'] .= "($end_mileage)";
            }
        }
        if ($back_mileage) {
            if ($back_mileage <= $event['end_mileage']) {
                $this->error('结束公里数不能小于起始公里数');
            }
            $data['content'] = '备注:' . $data['content'] . '<br>出行方式:' . $event['car_type'];
            if ($end_mileage) {
                $data['content'] .= "($back_mileage)";
            }
        }

        Db::startTrans();
        try {

            //创建签到记录
            StaffSignIn::createSignIn($data);
            //修改日程状态
            EventModel::updateProcess($event['id'], $event_process, $last_event);
            $update = [];
            if ($event_process == 3) {//
                $update = ['is_successful' => $is_successful, 'achieve_purpose' => $achieve_purpose];
            }
            //通话内容
            if ($call_content) {
                $update['call_content'] = $call_content;
            }
            if ($needs) {
                $update['needs'] = $needs;
            }
            if ($car_type) {//出行方式
                $update['car_type'] = $car_type;
                $update['car_number'] = $car_number;
            }
            if ($start_mileage) {//起始公里数
                $update['start_mileage'] = $start_mileage;
            }
            if ($end_mileage) {//结束公里数
                //根据 起始公里数 ，录入行程费用
                $mileage = $end_mileage - $event['start_mileage'];

                $mileage_consume = [
                    'title' => $event['title'] . '-路程费用',
                    'number' => Consume::getNumber(),
                    'customer_id' => $event['customer_id'],
                    'relation_id' => $event_id,
                    'relation_type' => Consume::EVENT_TYPE,
                    'submit_date' => date('Y-m-d'),
                    'remark' => '',
                    'money' => Consume::getMileageMoney($mileage)
                ];
                $files = StaffSignIn::where(['relation_type' => StaffSignIn::EVENT_TYPE, 'relation_id' => $event_id])->column('file_ids');
                $mileage_consume['detail'][] = [
                    'consume_date' => date('Y-m-d'),
                    'consume_type' => '交通费',
                    'consume_money' => Consume::getMileageMoney($mileage),
                    'mileage' => $mileage,
                    'car_number' => $event['car_number'],
                    'car_type' => $event['car_type'],
                    'start_mileage' => $event['start_mileage'],
                    'end_mileage' => $end_mileage,
                    'file_ids' => implode(',', $files)
                ];
                Consume::createConsume($mileage_consume);

                $update['end_mileage'] = $end_mileage;
            }
            if ($back_mileage) {//结束公里数
                //根据 起始公里数 ，录入行程费用
                $mileage = $back_mileage - $event['end_mileage'];

                $mileage_consume = [
                    'title' => $event['title'] . '-路程费用',
                    'number' => Consume::getNumber(),
                    'customer_id' => $event['customer_id'],
                    'relation_id' => $event_id,
                    'relation_type' => Consume::EVENT_TYPE,
                    'submit_date' => date('Y-m-d'),
                    'remark' => '',
                    'money' => Consume::getMileageMoney($mileage)
                ];
                $files = StaffSignIn::where(['relation_type' => StaffSignIn::EVENT_TYPE, 'relation_id' => $event_id])->column('file_ids');
                $mileage_consume['detail'][] = [
                    'consume_date' => date('Y-m-d'),
                    'consume_type' => '交通费',
                    'consume_money' => Consume::getMileageMoney($mileage),
                    'mileage' => $mileage,
                    'car_number' => $event['car_number'],
                    'car_type' => $event['car_type'],
                    'start_mileage' => $event['end_mileage'],
                    'end_mileage' => $back_mileage,
                    'file_ids' => implode(',', $files)
                ];
                Consume::createConsume($mileage_consume);

                $update['back_mileage'] = $back_mileage;
            }

            if ($update) {
                $model = new EventModel;
                $model->save($update, ['id' => $event['id']]);
            }
            if ($consume) {
                $consume['title'] = $event['title'] . '-出发费用';
                $consume['customer_id'] = $event['customer_id'];
                $consume['relation_type'] = Consume::EVENT_TYPE;
                $consume['relation_id'] = $event_id;

                Consume::createConsume($consume);
            }

            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            Log::error('错误:' . $e->getMessage());
            $this->error($e->getMessage());
        }

        $status_text = [1 => '开始任务', 2 => '签到成功', 3 => '完成任务', 4 => '返程签到成功'];
        $this->success($status_text[$event_process_text] ?? $event_process_text);
    }

    //修改日程状态
    public function updateStatus()
    {
        //日程状态 0未开始 1开始任务 2 已结束 3 已取消
        $status = input('status');
        $file_ids = input('file_ids');
        $event_id = input('event_id');
        $content = input('content');


        $where = ['id' => $event_id];
        $event = EventModel::where($where)->find();
        if (empty($event)) {
            $this->error('日程不存在');
        }

        $status_text = [1 => '开始任务', 2 => '完成任务', 3 => '任务终止'];
        $data = [
            'staff_id' => $this->auth->id,
            'file_ids' => $file_ids,
            'customer_id' => $event['relation_id'],//客户id
            'relation_process' => $status_text[$status] ?? '进行中',//日程类型
            'relation_type' => StaffSignIn::EVENT_TYPE,//日程类型
            'relation_id' => $event['id'],//签到关联id
            'content' => $content,
        ];
        Db::startTrans();
        try {
            //创建签到记录
            StaffSignIn::createSignIn($data);
            //修改日程状态
            EventModel::changeStatus($event['id'], $status);
            if ($status == 2) {
                Message::addMessage(StaffSignIn::EVENT_TYPE, $event['id'], $event['owner_staff_id'], $this->auth->id, "任务《{$event['title']}》已完成，请及时审阅!");
            } elseif ($status == 3) {
                Message::addMessage(StaffSignIn::EVENT_TYPE, $event['id'], $event['create_staff_id'], $this->auth->id, "任务《{$event['title']}》被终止，请及时审阅!");
            }
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            Log::error('错误:' . $e->getMessage());
            $this->error($e->getMessage());
        }

        $this->success('操作成功');
    }

    //获取签到信息
    public function getSign()
    {
        $customer_id = input('customer_id', 0, 'intval');
        $event_id = input('event_id', 0, 'intval');
        $limit = input('limit', 0);
        $where = [
//            'staff_id' => ['in', \addons\kuerp\model\Staff::getMyStaffIds()],

            'relation_type' => StaffSignIn::EVENT_TYPE,
        ];
        if ($event_id) {
            $where['relation_id'] = $event_id;
        }
        if ($customer_id) {
            $where['customer_id'] = $customer_id;
        }

        $staffSign = StaffSignIn::where($where)->with(['staff', 'customer'])->order('id desc')->paginate($limit);

        //标记 日程已读
        Message::where([
            'relation_type' => Message::RECORD_TYPE,
            'to_staff_id' => $this->auth->id,
            'status' => 0
        ])->update(['read_time' => time(), 'status' => 1]);

        $this->success('请求成功', $staffSign);
    }

    //指派负责人
    public function assign_event()
    {
        $id = input('id');
        $staff_id = input('staff_id');
        $desc = input('desc');
        $row = EventModel::where(['id' => $id])->find();
        if (empty($row)) {
            $this->error('日程信息不存在');
        }
        $staff = \addons\kuerp\model\Staff::info();
        $data = [

            'staff_id' => $this->auth->id,
            'customer_id' => $row['relation_id'],//客户id
            'relation_type' => StaffSignIn::EVENT_TYPE,//日程类型
            'relation_id' => $row['id'],//签到关联id
            'relation_process' => '指派负责人',//进度
            'content' => $staff->name . '指派负责人',
        ];
        Db::startTrans();
        try {
            //创建签到记录
            StaffSignIn::createSignIn($data);

            EventModel::where(['id' => $id])->update([
                'staff_id' => $staff_id,
            ]);
            //发送通知
            Message::addMessage(Message::EVENT_TYPE, $id, $staff_id, $staff->id,
                $staff->name . '指派给您一项任务，请您及时接受！');
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        $this->success('指派成功');
    }

    //完成日程
    public function complete_event()
    {
        $id = input('id');
        $is_successful = input('is_successful');
        $achieve_purpose = input('achieve_purpose', '');


        $row = EventModel::where(['id' => $id])->find();
        if (empty($row)) {
            $this->error('日程信息不存在');
        }
        $staff = \addons\kuerp\model\Staff::info();
        $data = [

            'staff_id' => $this->auth->id,
            'customer_id' => $row['relation_id'],//客户id
            'relation_type' => StaffSignIn::EVENT_TYPE,//日程类型
            'relation_id' => $row['id'],//签到关联id
            'relation_process' => '完成日程',//进度
            'content' => $staff->name . '完成日程',
        ];
        Db::startTrans();
        try {
            //创建签到记录
            StaffSignIn::createSignIn($data);
            EventModel::where(['id' => $id])->update(['is_successful' => $is_successful, 'achieve_purpose' => $achieve_purpose, 'status' => 2]);
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        $this->success('指派成功');
    }


    //撤销任务
    public function revokeEvent()
    {
        //日程状态 0未开始 1开始任务 2 已结束 3 已取消
        $event_id = input('event_id');
        $content = input('content', '');

        $where = ['id' => $event_id];
        $event = EventModel::where($where)->find();
        if (empty($event)) {
            $this->error('日程不存在');
        }
        if ($event['staff_id'] != $this->auth->id) {
            $this->error('只有任务负责人才能撤销任务');
        }

        $data = [

            'staff_id' => $this->auth->id,
            'customer_id' => $event['relation_id'],//客户id
            'relation_process' => '撤销任务',//日程类型
            'relation_type' => StaffSignIn::EVENT_TYPE,//日程类型
            'relation_id' => $event['id'],//签到关联id
            'content' => $content,
        ];
        Db::startTrans();
        try {
            //创建签到记录
            StaffSignIn::createSignIn($data);
            //修改日程状态
            EventModel::where(['id' => $event_id])->update(['process' => 0, 'staff_id' => $event['create_staff_id']]);
            Message::addMessage(StaffSignIn::EVENT_TYPE, $event['id'],$event['create_staff_id'], $this->auth->id, "任务《{$event['title']}》已撤销，请及时审阅!");
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            Log::error('错误:' . $e->getMessage());
            $this->error($e->getMessage());
        }

        $this->success('操作成功');
    }


    /**
     * 添加外勤签到
     */
    public function addOutSign()
    {
        $params = $this->request->post();
        $lng = input('lng');
        $lat = input('lat');
        if (empty($lng) || empty($lat)) {
            $this->error('地理位置不能为空');
        }
        $result = FormField::checkFields(FormField::SIGNIN_TYPE, $params);
        if ($result !== true) {
            $this->error($result);
        }
        $other = [];
        foreach ($params as $name => $val) {
            if (strstr($name, 'other_') !== false) {
                if (is_array($val)) {
                    $other[$name] = implode(',', $val);
                } else {
                    $other[$name] = $val;
                }
                unset($params[$name]);
            } else {
                if ($params[$name] === '') {
                    $params[$name] = NULL;
                }
            }
        }
        //获取客户信息
        $customer = Customers::where(['id' => $params['customer_id']])->find();
        if (empty($customer)) {
            $this->error('客户不存在');
        }
        if (empty($customer['lng']) && !empty($customer['address'])) {
            $address = (strpos($customer['address'], '市') === false && !empty($customer['mergename']) ? str_replace(',', '', $customer['mergename']) : '' ) . $customer['address'];
            $map_key= AdminConfig::getConfigValue('map_key','wechat');
            if(empty($map_key)){
                $this->error('腾讯地图key未设置，请联系管理员设置！');
            }
            try{
                $address = urlencode($address);
                $url="https://apis.map.qq.com/ws/geocoder/v1/?address={$address}&key={$map_key}";
                $result=file_get_contents($url);
                Log::write('map-event---'.$result);
                $result=json_decode($result,true);
                if ($result['status']==0) {
                    $customer['lng']=$result['result']['location']['lng'];
                    $customer['lat']=$result['result']['location']['lat'];
                    Customers::where(['id' => $customer['id']])->update(['lng'=>$customer['lng'],'lat'=>$customer['lat']]);
                }
            } catch (\Exception $e) {
                Log::write('map-event---获取位置报错：'.$e->getMessage());
            }
        }
        if (empty($customer['lng'])) {
            $this->error('客户地址未设置！');
        }
        $params['distance'] = getdistance($lng, $lat, $customer['lng'], $customer['lat']);
        $max_distance = config('site.sign_max_distance');
        if ($max_distance && $params['distance'] > $max_distance) {
            $this->error('距离超过'.$max_distance.'米，不能签到');
        }
        $params['relation_process'] = '拜访签到';
        $params['staff_id'] = $this->auth->staff_member_id;
        $params['other'] = json_encode($other, JSON_UNESCAPED_UNICODE);
        $model = new StaffSignIn();
        if ($model->allowField(true)->save($params)) {
            $lastId = $model->getLastInsID();
            //通知上级
            //获取当前用户上级
            if($this->auth->parentids && !in_array(2,$this->auth->group_ids)) {
                foreach ($this->auth->parentids as $parent) {
                    Message::addMessage(Message::SIGN_TYPE, $lastId, $parent, $this->auth->id);
                }
            }
            $this->success('签到成功');
        }
        $this->error('签到失败');
    }

    /**
     * 获取外勤签到列表
     */
    public function getOutSign()
    {
        $customer_id = input('customer_id', 0, 'intval');
        $limit = input("limit/d", 10);
        $params = $this->request->post();

        $where = FormField::updateWhereField(FormField::SIGNIN_TYPE, $params);

        $type = input('type', 0);// 0 全部 1 我创建 2 下属创建

        if ($type == 1) {//我的客户
            $where['staff_id'] = $this->auth->staff_member_id;
        } elseif ($type == 2) {//下属负责的客户
            $sale_users = $this->auth->sale_users;
            //本人存在 则剔除自己
            if (in_array($this->auth->staff_member_id,$sale_users)) {
                $sale_users = array_diff($sale_users, [$this->auth->staff_member_id]);
            }
            $where['staff_id'] = ['in', $sale_users];
        } else {
            $where['staff_id'] = ['in', $this->auth->sale_users];
        }
        if ($customer_id) {
            $where['customer_id'] = $customer_id;
        }
        $where['relation_process'] = '拜访签到';
        $staffSign = StaffSignIn::where($where)->with(['staff', 'customer'])
            ->order('id desc')->paginate($limit);
        $staffSign = $staffSign->toArray();
        if ($staffSign['data']) {
            $adminIds = array_column(array_column($staffSign['data'], 'staff'), 'admin_id');
            $adminIds = array_unique($adminIds);
            $adminList = Admin::where('id', 'in', $adminIds)->field('id,nickname,avatar')->select();
        }
        foreach ($staffSign['data'] as $k => &$v) {
            $v['staff']['nickname'] = $adminList[$v['staff']['admin_id']]['nickname'] ?? $v['staff']['name'];
            $avatar = $adminList[$v['staff']['admin_id']]['avatar'] ?? '';
            $avatar = $avatar ? $avatar : '/assets/img/avatar.png';
            $avarar = cdnurl($avatar, true);//strpos($avatar, 'http') === false ? request()->domain() . $avatar : $avatar;
            $v['staff']['avatar'] = $avarar;
        }
        //标记通知已读
        Message::setRead(Message::SIGN_TYPE, 0, $this->auth->id);
        $this->success('请求成功', $staffSign);
    }

    /**
     * 获取签到详情
     */
    public function getOutSignDetail()
    {
        $id = input('id', 0, 'intval');

        $staffSign = StaffSignIn::where(['id' => $id])->with(['staff', 'customer'])->find();
        if (empty($staffSign)) {
            $this->error('数据不存在');
        }
        $staffSign = $staffSign->toArray();
        $other = json_decode($staffSign['other'], true);
        $staffSign = array_merge($staffSign, $other);
        $staffSign = Form::getDataDetail(Form::SIGNIN_TYPE, $staffSign);
        if (!empty($staffSign)) {
            $admin_info = Admin::where('id', $staffSign['staff']['admin_id'])->field('nickname,avatar')->find();
            $staffSign['staff']['nickname'] = $admin_info['nickname'];
            $staffSign['staff']['avatar'] = cdnurl($admin_info['avatar'] ?? '/assets/img/avatar.png', true);//$admin_info['avatar'] ? strpos($admin_info['avatar'], 'http') === false ? request()->domain() . $admin_info['avatar'] : $admin_info['avatar'] : '/assets/img/avatar.png';
        }
        //标记通知已读
		Message::setRead(Message::SIGN_TYPE, $id, $this->auth->id);
        $this->success('请求成功', $staffSign);
    }
}
